﻿create procedure [dbo].[usp_MachineInsert]
	@MachineName nvarchar(100)
	, @MachineIPAddress nvarchar(100)
	, @OperatingSystem nvarchar(100)
	, @ProcessorCount int
	, @InstalledMemory bigint
	, @InstalledMemorySpeed int
as

begin try
	
	begin transaction
	
		if not exists(select * from [dbo].[Machine] where (MachineName = @MachineName or (MachineName is null and @MachineName is null)) and
			                                              (MachineIPAddress = @MachineIPAddress or (MachineIPAddress is null and @MachineIPAddress is null)) and 
				                                          (OperatingSystem = @OperatingSystem or (OperatingSystem is null and @OperatingSystem is null)) and
					                                      (ProcessorCount = @ProcessorCount or (ProcessorCount is null and @ProcessorCount is null)) and
					                                      (InstalledMemory = @InstalledMemory or (InstalledMemory is null and @InstalledMemory is null)) and
					                                      (InstalledMemorySpeed = @InstalledMemorySpeed or (InstalledMemorySpeed is null and @InstalledMemorySpeed is null)))
			begin
										                              
				insert [dbo].[Machine]
				(
					MachineName
					, MachineIPAddress
					, OperatingSystem
					, ProcessorCount
					, InstalledMemory
					, InstalledMemorySpeed
				)
				values
				(
					@MachineName
					, @MachineIPAddress
					, @OperatingSystem
					, @ProcessorCount
					, @InstalledMemory
					, @InstalledMemorySpeed
				)
				
				select MachineId, ConcurrencyId, Created, Updated from [dbo].[Machine] where @@rowcount > 0 and MachineId = scope_identity()
			
			end
			
		else
			
			begin
			
				select MachineId, ConcurrencyId, Created, Updated from [dbo].[Machine] where (MachineName = @MachineName or (MachineName is null and @MachineName is null)) and
			                                                                                 (MachineIPAddress = @MachineIPAddress or (MachineIPAddress is null and @MachineIPAddress is null)) and 
				                                                                             (OperatingSystem = @OperatingSystem or (OperatingSystem is null and @OperatingSystem is null)) and
					                                                                         (ProcessorCount = @ProcessorCount or (ProcessorCount is null and @ProcessorCount is null)) and
					                                                                         (InstalledMemory = @InstalledMemory or (InstalledMemory is null and @InstalledMemory is null)) and
					                                                                         (InstalledMemorySpeed = @InstalledMemorySpeed or (InstalledMemorySpeed is null and @InstalledMemorySpeed is null))
			end
	
	commit transaction

end try
	
begin catch
	if @@trancount > 0
	begin
		rollback transaction;
	end
	execute [dbo].[usp_SqlErrorInsert]
end catch


